package com.ssy.lingxi.member.merchant.serviceimpl.feign;

import cn.hutool.core.util.ObjectUtil;
import com.querydsl.core.types.Projections;
import com.querydsl.jpa.impl.JPAQuery;
import com.querydsl.jpa.impl.JPAQueryFactory;
import com.ssy.lingxi.common.constant.Constants;
import com.ssy.lingxi.common.constant.basic.EnableDisableStatus;
import com.ssy.lingxi.common.constant.member.RoleTypeEnum;
import com.ssy.lingxi.common.exception.BusinessException;
import com.ssy.lingxi.common.model.dto.UserLoginCacheDTO;
import com.ssy.lingxi.common.response.PageData;
import com.ssy.lingxi.common.response.ResponseCode;
import com.ssy.lingxi.common.response.Wrapper;
import com.ssy.lingxi.dataauth.handler.RedisServiceHolder;
import com.ssy.lingxi.dataauth.model.constant.DataAuthConstant;
import com.ssy.lingxi.dataauth.model.dto.DataAuthDto;
import com.ssy.lingxi.member.merchant.api.model.vo.inner.request.MemberSalesCountFeignVO;
import com.ssy.lingxi.member.merchant.api.model.vo.inner.request.MemberSalesFindMemberVO;
import com.ssy.lingxi.member.merchant.api.model.vo.inner.request.MemberSalesFindUserIdVO;
import com.ssy.lingxi.member.merchant.api.model.vo.inner.response.*;
import com.ssy.lingxi.member.merchant.entity.*;
import com.ssy.lingxi.member.merchant.model.constant.MemberUserAuthTypeEnum;
import com.ssy.lingxi.member.merchant.model.vo.basic.response.ChannelListVO;
import com.ssy.lingxi.member.merchant.model.vo.basic.response.MemberSalesChannelFindUserIdQueryVO;
import com.ssy.lingxi.member.merchant.repository.*;
import com.ssy.lingxi.member.merchant.service.base.IBaseMemberCacheService;
import com.ssy.lingxi.member.merchant.service.feign.IMemberAbilitySalesFeignService;
import com.ssy.lingxi.member.merchant.utils.MemberOrganizationUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.persistence.criteria.Join;
import javax.persistence.criteria.JoinType;
import javax.persistence.criteria.Predicate;
import java.net.URI;
import java.util.*;
import java.util.stream.Collectors;

/**
 * Web端-业务员业绩统计相关接口
 *
 * @author 郑小翠
 * @version 2.02.18
 * @date 2022-03-29
 */
@Service
public class MemberAbilitySalesFeignServiceImpl implements IMemberAbilitySalesFeignService {

    @Resource
    private MemberRepository memberRepository;

    @Resource
    private MemberUserRepository memberUserRepository;

    @Resource
    private IBaseMemberCacheService memberCacheService;

    @Resource
    private JPAQueryFactory jpaQueryFactory;

    /**
     * 远程调用 - 分页查询已经绑定渠道的业务员列表
     *
     * @param pageVO 接口参数
     * @return 返回符合条件的业务员列表和下级会员，以及消费者角色Id
     */
    @Override
    public Wrapper<PageData<MemberFeignSalesCountVO>> getMemberSalesList(MemberSalesCountFeignVO pageVO) {
        // 找到所有的业务员
        Wrapper<PageData<MemberUserDO>> userList = getMemberUserList(pageVO);
        if (CollectionUtils.isEmpty(userList.getData().getData())) {
            return Wrapper.success(new PageData<>(0L, new ArrayList<>()));
        }
        List<MemberUserDO> memberUserList = userList.getData().getData();

        // 会员关系Id
        List<Long> relationIds = memberUserList.stream().flatMap(userDO -> {
            List<MemberUserChannelDO> collect = userDO.getUserAuth().getChannels().stream().filter(channel -> channel.getRoleId().equals(pageVO.getMemberRoleId())).collect(Collectors.toList());
            return collect.stream().map(MemberUserChannelDO::getMemberRelationId);
        }).collect(Collectors.toList());

        // 查找业务员下面的会员,会员类型为消费者
        if (ObjectUtil.isNotNull(relationIds)) {
            QMemberUserChannelDO qMemberUserChannelDO = QMemberUserChannelDO.memberUserChannelDO;
            QMemberRelationDO qMemberRelationDO = QMemberRelationDO.memberRelationDO;
            QMemberUserDO qMemberUserDO = QMemberUserDO.memberUserDO;
            QRoleDO qRoleDO = QRoleDO.roleDO;
            QRoleTypeDO qRoleTypeDO = QRoleTypeDO.roleTypeDO;
            JPAQuery<MemberSalesFindMemberQueryListVO> query = jpaQueryFactory.select(Projections.constructor(MemberSalesFindMemberQueryListVO.class, qMemberUserChannelDO.userId, qMemberUserDO.name, qMemberUserChannelDO.subMemberId, qMemberUserChannelDO.subRoleId, qMemberUserChannelDO.createTime))
                    .from(qMemberUserChannelDO)
                    .leftJoin(qMemberUserDO).on(qMemberUserChannelDO.userId.eq(qMemberUserDO.id))
                    .leftJoin(qMemberRelationDO).on(qMemberUserChannelDO.memberRelationId.eq(qMemberRelationDO.id))
                    .leftJoin(qRoleDO).on(qMemberRelationDO.subRoleId.eq(qRoleDO.id))
                    .leftJoin(qRoleTypeDO).on(qRoleDO.roleType.eq(qRoleTypeDO))
                    .where(qMemberRelationDO.id.in(relationIds))
                    .where(qRoleTypeDO.typeEnum.eq(RoleTypeEnum.SERVICE_CONSUMER.getCode()))
                    .orderBy(qMemberUserChannelDO.id.desc());

            List<MemberSalesFindMemberQueryListVO> queryList = query.fetch();
            // 根据会员Id和角色Id去重
            ArrayList<MemberSalesFindMemberQueryListVO> memberQueryList = queryList.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(user -> user.getMemberId() + ";" + user.getRoleId()))), ArrayList::new));
            // 为每个业务员添加组织机构
            List<List<MemberSalesFindMemberQueryListVO>> lists = new ArrayList<>();
            for (MemberSalesFindMemberQueryListVO memberSalesForVO : memberQueryList) {
                List<MemberSalesFindMemberQueryListVO> addMemberOrganizationList = memberUserList.stream().filter(user -> user.getId().equals(memberSalesForVO.getUserId())).map(user -> {
                    List<MemberOrganizationDO> orgList = new ArrayList<>(user.getMember().getOrgs());
                    MemberSalesFindMemberQueryListVO queryVO = new MemberSalesFindMemberQueryListVO();
                    BeanUtils.copyProperties(memberSalesForVO, queryVO);
                    queryVO.setOrgName(MemberOrganizationUtil.joinTitleToString(user.getOrg() == null ? 0L : user.getOrg().getId(), orgList));
                    return queryVO;
                }).collect(Collectors.toList());
                lists.add(addMemberOrganizationList);
            }
            List<MemberSalesFindMemberQueryListVO> memberSalesFindMemberQueryList = lists.stream().flatMap(Collection::stream).collect(Collectors.toList());

            // 找到所有 有下级会员的业务员，并将业务员信息和下级会员信息形成要返回出去的VO，就是MemberSalesCountQueryVO
            // 最后收集成业务员列表List<MemberSalesCountQueryVO> memberSalesCountQueryVOList
            List<MemberFeignSalesCountVO> memberSalesCountQueryVOList = memberSalesFindMemberQueryList.stream().collect(Collectors.groupingBy(MemberSalesFindMemberQueryListVO::getUserId)).entrySet().stream()
                    .map(memberSalesCountQueryEntry -> {
                        Long userId = memberSalesCountQueryEntry.getKey();
                        List<MemberSalesFindMemberQueryListVO> queryVO = memberSalesCountQueryEntry.getValue();
                        MemberFeignSalesCountVO memberSalesQueryVO = new MemberFeignSalesCountVO();
                        memberSalesQueryVO.setOrgName(queryVO.get(0).getOrgName());
                        memberSalesQueryVO.setUserId(userId);
                        memberSalesQueryVO.setTotalCount(queryVO.size());
                        memberSalesQueryVO.setName(queryVO.get(0).getName());
                        List<MemberFeignUserListVO> channelCountList = queryVO.stream().map(countQuery -> {
                            MemberFeignUserListVO countQueryVO = new MemberFeignUserListVO();
                            countQueryVO.setMemberId(countQuery.getMemberId());
                            countQueryVO.setRoleId(countQuery.getRoleId());
                            return countQueryVO;
                        }).collect(Collectors.toList());
                        memberSalesQueryVO.setMemberFeignUserListVO(channelCountList);
                        return memberSalesQueryVO;
                    }).collect(Collectors.toList());

            // 当最后的业务员数量与之前的所有业务员数量不匹配，说明该业务员下面的会员不是消费者，或者还没有下级会员
            // 那就把该业务员追加到要返回出去的VO里，也就是List<MemberSalesCountQueryVO> memberSalesCountQueryVOList里，并将该业务员的下级会员数设置为0，下级会员列表设置为null
            List<Long> userIds = memberSalesCountQueryVOList.stream().map(MemberFeignSalesCountVO::getUserId).collect(Collectors.toList());
            List<MemberFeignSalesCountVO> memberSalas = memberUserList.stream().filter(user -> !userIds.contains(user.getId())).map(user -> {
                MemberFeignSalesCountVO memberSalesCountQueryVO = new MemberFeignSalesCountVO();
                // 下级会员数
                memberSalesCountQueryVO.setTotalCount(0);
                memberSalesCountQueryVO.setUserId(user.getId());
                memberSalesCountQueryVO.setName(user.getName());
                // 组织机构名
                List<MemberOrganizationDO> orgList = new ArrayList<>(user.getMember().getOrgs());
                memberSalesCountQueryVO.setOrgName(MemberOrganizationUtil.joinTitleToString(user.getOrg() == null ? 0L : user.getOrg().getId(), orgList));
                memberSalesCountQueryVO.setMemberFeignUserListVO(new ArrayList<>());
                return memberSalesCountQueryVO;
            }).collect(Collectors.toList());

            memberSalesCountQueryVOList.addAll(memberSalas);

            return Wrapper.success(new PageData<>(userList.getData().getTotalCount(), memberSalesCountQueryVOList));
        }

        return Wrapper.success(new PageData<>(0L, new ArrayList<>()));
    }

    /**
     * 获取角色类型为消费者的角色Id
     *
     * @return 返回角色类型为消费者的角色Id
     */
    @Override
    public Wrapper<List<Long>> getRoleIds() {
        QRoleDO qRoleDO = QRoleDO.roleDO;
        QRoleTypeDO qRoleTypeDO = QRoleTypeDO.roleTypeDO;
        JPAQuery<Long> query = jpaQueryFactory.select(Projections.constructor(Long.class, qRoleDO.id))
                .from(qRoleDO)
                .leftJoin(qRoleTypeDO).on(qRoleDO.roleType.eq(qRoleTypeDO))
                .where(qRoleTypeDO.typeEnum.eq(RoleTypeEnum.SERVICE_CONSUMER.getCode()));

        List<Long> memberQueryList = query.fetch();
        return Wrapper.success(query.fetch());
    }

    /**
     * 远程调用 - 分页查询该业务员下面的渠道会员
     *
     * @param pageVO 下级会员搜索条件
     * @return 下级会员信息
     */
    @Override
    public Wrapper<PageData<MemberSalesFeignPageQueryVO>> findByUserId(MemberSalesFindUserIdVO pageVO) {
        MemberUserDO userDO = memberUserRepository.findById(pageVO.getUserId()).orElse(null);
        if (userDO == null || userDO.getMember() == null || !userDO.getMember().getId().equals(pageVO.getMemberId())) {
            return Wrapper.fail(ResponseCode.MC_MS_MEMBER_USER_DOES_NOT_EXIST);
        }

        if (userDO.getIsSales() == null || userDO.getIsSales().equals(EnableDisableStatus.DISABLE.getCode())) {
            return Wrapper.fail(ResponseCode.MC_MS_MEMBER_USER_IS_NOT_SALES);
        }

        // 找到全部的下级会员
        List<MemberUserChannelDO> channels = userDO.getUserAuth().getChannels().stream().filter(channel -> channel.getRoleId().equals(pageVO.getMemberRoleId())).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(channels)) {
            return Wrapper.success(new PageData<>(0L, new ArrayList<>()));
        }

        // 关系Id
        List<Long> relationIds = channels.stream().map(MemberUserChannelDO::getMemberRelationId).collect(Collectors.toList());

        // 根据关系Id结合用户输入查询条件 找到所有的下级会员并返回VO对象
        if (ObjectUtil.isNotNull(relationIds)) {

            QMemberUserChannelDO qMemberUserChannelDO = QMemberUserChannelDO.memberUserChannelDO;
            QMemberRelationDO qMemberRelationDO = QMemberRelationDO.memberRelationDO;
            QMemberUserDO qMemberUserDO = QMemberUserDO.memberUserDO;
            QRoleDO qRoleDO = QRoleDO.roleDO;
            QRoleTypeDO qRoleTypeDO = QRoleTypeDO.roleTypeDO;
            JPAQuery<MemberSalesFeignPageQueryVO> query =
                    jpaQueryFactory.select(Projections.constructor(MemberSalesFeignPageQueryVO.class, qMemberUserChannelDO.subMemberId, qMemberRelationDO.subMember.name, qMemberRelationDO.subRoleId, qMemberRelationDO.subRole.roleName, qMemberUserChannelDO.createTime))
                            .from(qMemberUserChannelDO)
                            .leftJoin(qMemberUserDO).on(qMemberUserChannelDO.userId.eq(qMemberUserDO.id))
                            .leftJoin(qMemberRelationDO).on(qMemberUserChannelDO.memberRelationId.eq(qMemberRelationDO.id))
                            .leftJoin(qRoleDO).on(qMemberRelationDO.subRoleId.eq(qRoleDO.id))
                            .leftJoin(qRoleTypeDO).on(qRoleDO.roleType.eq(qRoleTypeDO))
                            .where(qRoleTypeDO.typeEnum.eq(RoleTypeEnum.SERVICE_CONSUMER.getCode()))
                            .where(qMemberUserChannelDO.userId.eq(pageVO.getUserId()))
                            .where(qMemberRelationDO.id.in(relationIds));
            // 下级会员名称
            if (StringUtils.hasLength(pageVO.getMemberName())) {
                query.where(qMemberRelationDO.subMember.name.eq(pageVO.getMemberName()));
            }
            if (pageVO.getCurrent() != 0 && pageVO.getPageSize() != 0) {
                query.limit(pageVO.getPageSize()).offset((long) (pageVO.getCurrent() - 1) * pageVO.getPageSize());
            }
            //总数
            long totalCount = query.fetchCount();

            // 所有下级会员信息
            List<MemberSalesFeignPageQueryVO> queryList = query.orderBy(qMemberUserChannelDO.id.desc()).fetch();
            ArrayList<MemberSalesFeignPageQueryVO> result = queryList.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(user -> user.getMemberId() + ";" + user.getMemberRoleId()))), ArrayList::new));
            return Wrapper.success(new PageData<>(totalCount, result));
        }

        return Wrapper.success(new PageData<>(0L, new ArrayList<>()));
    }

    /**
     * 远程调用 - 查询已经绑定渠道的业务员列表
     *
     * @param pageVO 接口参数
     * @return 返回下级会员信息
     */
    @Override
    public Wrapper<List<MemberSalesFindMemberQueryVO>> findMemberSales(MemberSalesFindMemberVO pageVO) {

        MemberDO memberDO = memberRepository.findById(pageVO.getMemberId()).orElse(null);
        if (memberDO == null) {
            return Wrapper.fail(ResponseCode.MC_MS_MEMBER_DOES_NOT_EXIST);
        }

        // 根据登录的会员Id找到下面的业务员
        Specification<MemberUserDO> specification = (root, query, criteriaBuilder) -> {
            List<Predicate> list = new ArrayList<>();

            //注意这里的写法，会转换为查询member_id
            list.add(criteriaBuilder.equal(root.get("member").as(MemberDO.class), pageVO.getMemberId()));
            list.add(criteriaBuilder.equal(root.get("isSales").as(Integer.class), EnableDisableStatus.ENABLE.getCode()));
            list.add(criteriaBuilder.equal(root.get("typeEnum").as(Integer.class), MemberUserAuthTypeEnum.NORMAL.getCode()));

            if (ObjectUtil.isNotNull(pageVO.getUserId())) {
                list.add(criteriaBuilder.equal(root.get("id").as(Long.class), pageVO.getUserId()));
            }

            Predicate[] p = new Predicate[list.size()];
            return criteriaBuilder.and(list.toArray(p));
        };
        List<MemberUserDO> memberUserList = memberUserRepository.findAll(specification);

        // 会员关系Id
        List<Long> relationIds = memberUserList.stream().flatMap(userDO -> {
            List<MemberUserChannelDO> collect = userDO.getUserAuth().getChannels().stream().filter(channel -> channel.getRoleId().equals(pageVO.getMemberRoleId())).collect(Collectors.toList());
            return collect.stream().map(MemberUserChannelDO::getMemberRelationId);
        }).collect(Collectors.toList());

        // 根据关系Id结合用户输入查询条件 找到所有的下级会员
        if (ObjectUtil.isNotNull(relationIds)) {
            QMemberUserChannelDO qMemberUserChannelDO = QMemberUserChannelDO.memberUserChannelDO;
            QMemberRelationDO qMemberRelationDO = QMemberRelationDO.memberRelationDO;
            QMemberUserDO qMemberUserDO = QMemberUserDO.memberUserDO;
            QRoleDO qRoleDO = QRoleDO.roleDO;
            QRoleTypeDO qRoleTypeDO = QRoleTypeDO.roleTypeDO;
            JPAQuery<MemberSalesFindMemberQueryVO> query = jpaQueryFactory.select(Projections.constructor(MemberSalesFindMemberQueryVO.class, qMemberUserChannelDO.userId, qMemberUserDO.name, qMemberUserChannelDO.subMemberId, qMemberUserChannelDO.subRoleId, qMemberUserChannelDO.createTime))
                    .from(qMemberUserChannelDO)
                    .leftJoin(qMemberUserDO).on(qMemberUserChannelDO.userId.eq(qMemberUserDO.id))
                    .leftJoin(qMemberRelationDO).on(qMemberUserChannelDO.memberRelationId.eq(qMemberRelationDO.id))
                    .leftJoin(qRoleDO).on(qMemberRelationDO.subRoleId.eq(qRoleDO.id))
                    .leftJoin(qRoleTypeDO).on(qRoleDO.roleType.eq(qRoleTypeDO))
                    .where(qMemberRelationDO.id.in(relationIds))
                    .where(qRoleTypeDO.typeEnum.eq(RoleTypeEnum.SERVICE_CONSUMER.getCode()))
                    .orderBy(qMemberUserChannelDO.id.desc());

            if (ObjectUtil.isNotNull(pageVO.getStartTime())) {
                query.where(qMemberUserChannelDO.createTime.before(pageVO.getStartTime()));
            }
            // 业务员Id
            if (ObjectUtil.isNotNull(pageVO.getUserId())) {
                query.where(qMemberUserChannelDO.userId.eq(pageVO.getUserId()));
            }
            // 下级会员Id
            if (ObjectUtil.isNotNull(pageVO.getSubMemberId())) {
                query.where(qMemberUserChannelDO.subMemberId.eq(pageVO.getSubMemberId()));
            }
            // 下级会员角色Id
            if (ObjectUtil.isNotNull(pageVO.getSubMemberRoleId())) {
                query.where(qMemberUserChannelDO.subRoleId.eq(pageVO.getSubMemberRoleId()));
            }
            // 下级会员名称
            if (StringUtils.hasLength(pageVO.getSubMemberName())) {
                query.where(qMemberRelationDO.subMember.name.eq(pageVO.getSubMemberName()));
            }

            // 所有下级会员信息
            List<MemberSalesFindMemberQueryVO> result = query.fetch();

            return Wrapper.success(result);
        }
        return Wrapper.success(new ArrayList<>());

    }

    /**
     * 查看业务员详情
     *
     * @param headers 头部信息
     * @param userId  用户Id
     * @return 返回业务员信息
     */
    @Override
    public Wrapper<MemberSalesChannelFindUserIdQueryVO> getChannelInformation(HttpHeaders headers, Long userId) {
        UserLoginCacheDTO loginUser = memberCacheService.needLoginFromBusinessPlatform(headers);
        MemberUserDO userDO = memberUserRepository.findById(userId).orElse(null);
        if (ObjectUtil.isNotNull(userDO)) {
            // 该角色是否有权限查看
            List<MemberUserChannelDO> channels = userDO.getUserAuth().getChannels().stream().filter(channel -> channel.getRoleId().equals(loginUser.getMemberRoleId())).collect(Collectors.toList());
            if (CollectionUtils.isEmpty(channels)) {
                return Wrapper.success();
            }

            List<MemberOrganizationDO> orgList = new ArrayList<>(userDO.getMember().getOrgs());
            MemberSalesChannelFindUserIdQueryVO queryVO = new MemberSalesChannelFindUserIdQueryVO();
            queryVO.setUserId(userDO.getId());
            queryVO.setName(userDO.getName());
            queryVO.setRoleName(userDO.getRoles().stream().map(MemberRoleDO::getRoleName).collect(Collectors.joining(",")));
            queryVO.setTitle(MemberOrganizationUtil.joinTitleToString(userDO.getOrg() == null ? 0L : userDO.getOrg().getId(), orgList));
            queryVO.setCountryCode(StringUtils.hasLength(userDO.getCountryCode()) ? userDO.getCountryCode() : "");
            queryVO.setPhone(userDO.getPhone());
            queryVO.setPosition(StringUtils.hasLength(userDO.getJobTitle()) ? userDO.getJobTitle() : "");
            return Wrapper.success(queryVO);
        }
        return Wrapper.success();

    }

    /**
     * 订单能力-业绩统计-订单明细-业务员列表
     *
     * @param headers 头部信息
     * @return 返回业务员列表
     */
    @Override
    public Wrapper<List<ChannelListVO>> getChannelList(HttpHeaders headers) {
        UserLoginCacheDTO loginUser = memberCacheService.needLoginFromBusinessPlatform(headers);
        MemberSalesCountFeignVO vo = new MemberSalesCountFeignVO();
        Integer source = loginUser.getLoginSource();
        Long headerUserId = loginUser.getUserId();
        String token = headers.getFirst("token");
        String referer = headers.getFirst("Referer");
        String authUrl = "";
        try {
            assert referer != null;
            URI uri = new URI(referer);
            authUrl = uri.getPath();
        } catch (Exception ignored) {
        }
        // 从Redis缓存中读取用户数据权限配置，如果没有数据权限配置，则返回的是Null
        String dataAuthKey = String.format(DataAuthConstant.DATA_AUTH_CACHE_KEY_FORMAT, token, headerUserId, source);
        DataAuthDto dataAuthDto = (DataAuthDto) RedisServiceHolder.redisUtils.hGet(dataAuthKey, authUrl, Constants.REDIS_USER_INDEX);
        if (dataAuthDto != null) {
            List<Long> userIds = dataAuthDto.getUserIds();
            vo.setUserIds(userIds);
        }
        vo.setMemberId(loginUser.getMemberId());
        vo.setMemberRoleId(loginUser.getMemberRoleId());
        vo.setCurrent(1);
        vo.setPageSize(1000);
        Wrapper<PageData<MemberUserDO>> userList = getMemberUserList(vo);
        if (CollectionUtils.isEmpty(userList.getData().getData())) {
            return Wrapper.success();
        }
        // 找到所有的业务员
        List<MemberUserDO> memberUserList = userList.getData().getData();
        List<ChannelListVO> result = memberUserList.stream().map(user -> {
            ChannelListVO channelListVO = new ChannelListVO();
            channelListVO.setUserName(user.getName());
            channelListVO.setUserId(user.getId());
            return channelListVO;
        }).collect(Collectors.toList());
        return Wrapper.success(result);
    }

    /**
     * 根据数据权限展示业务员ID
     *
     * @param pageVO 查询条件
     * @return 返回符合条件的业务员
     */
    @Override
    public Wrapper<List<MemberUserVO>> getUserIds(MemberSalesCountFeignVO pageVO) {
        Wrapper<PageData<MemberUserDO>> memberUserList = getMemberUserList(pageVO);
        if (CollectionUtils.isEmpty(memberUserList.getData().getData())) {
            return Wrapper.success();
        }
        List<MemberUserDO> userList = memberUserList.getData().getData();
        List<MemberUserVO> result = userList.stream().map(user -> {
            MemberUserVO vo = new MemberUserVO();
            vo.setUserId(user.getId());
            vo.setUserName(user.getName());
            return vo;
        }).collect(Collectors.toList());
        return Wrapper.success(result);
    }

    /**
     * 根据数据权限展示业务员信息
     *
     * @param pageVO 查询条件
     * @return 返回符合条件的业务员
     */
    private Wrapper<PageData<MemberUserDO>> getMemberUserList(MemberSalesCountFeignVO pageVO) {
        Pageable pageable = PageRequest.of(pageVO.getCurrent() - 1, pageVO.getPageSize(), Sort.by("id").ascending());
        MemberDO memberDO = memberRepository.findById(pageVO.getMemberId()).orElse(null);
        if (memberDO == null) {
            throw new BusinessException(ResponseCode.MC_MS_MEMBER_DOES_NOT_EXIST);
        }

        Specification<MemberUserDO> specification = (root, query, criteriaBuilder) -> {
            List<Predicate> list = new ArrayList<>();

            // 注意这里的写法，会转换为查询member_id
            list.add(criteriaBuilder.equal(root.get("member").as(MemberDO.class), pageVO.getMemberId()));
            list.add(criteriaBuilder.equal(root.get("isSales").as(Integer.class), EnableDisableStatus.ENABLE.getCode()));
            list.add(criteriaBuilder.equal(root.get("typeEnum").as(Integer.class), MemberUserAuthTypeEnum.NORMAL.getCode()));

            if (StringUtils.hasLength(pageVO.getTitle())) {
                Join<MemberUserDO, MemberOrganizationDO> join = root.join("org", JoinType.LEFT);
                list.add(criteriaBuilder.like(join.get("title"), "%" + pageVO.getTitle() + "%"));
            }

            if (StringUtils.hasLength(pageVO.getName())) {
                list.add(criteriaBuilder.like(root.get("name").as(String.class), "%" + pageVO.getName().trim() + "%"));
            }
            if (!CollectionUtils.isEmpty(pageVO.getUserIds())) {
                list.add(criteriaBuilder.in(root.get("id")).value(pageVO.getUserIds()));
            }

            Predicate[] p = new Predicate[list.size()];
            return criteriaBuilder.and(list.toArray(p));
        };
        // 找到所有的业务员
        Page<MemberUserDO> result = memberUserRepository.findAll(specification, pageable);
        return Wrapper.success(new PageData<>(result.getTotalElements(), result.getContent()));
    }


}
